import { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'

import { apiGetWaybillPublishPath, apiGetWaybillStatusOverview } from './apis'
import { AddEvent, IAddEventProps } from './components/AddEvent'
import { IWaybillDetailRes, IWaybillPublishPathRes, StatusODTO } from './interface'

// AbortController（TabCount 专用）
export type TRequest = Result<IWaybillDetailRes, []>

export interface IStore {
  detail: IWaybillDetailRes
  request?: TRequest
  loading: boolean
  setDetail: (val: Partial<IWaybillDetailRes> | ((prevVal: IWaybillDetailRes) => IWaybillDetailRes)) => void
  openEventPopup: (val: IAddEventProps) => void
  // 轨迹模块
  waybillPublishPath: IWaybillPublishPathRes[]
  getEventList: (waybillNo: string) => Promise<void>
  getDetail: () => void
  waybillStatusOverview: StatusODTO[]
  getWaybillStatusOverview: (waybillNo: string) => Promise<void>
}

export const useBoundStore = create<IStore>((set, get) => {
  return {
    detail: {},
    loading: false,
    openEventPopup: (val: IAddEventProps) => AddEvent.open(val),
    setDetail: val => {
      set(prev => {
        return {
          detail: {
            ...prev.detail,
            ...(typeof val === 'function' ? val(prev.detail) : val),
          },
        }
      })
    },
    getDetail: () => {
      set({ loading: true })
      try {
        get().request?.run()
      } finally {
        set({ loading: false })
      }
    },
    // 状态模块
    waybillStatusOverview: [],
    getWaybillStatusOverview: async (waybillNo: string) => {
      const res = await apiGetWaybillStatusOverview({ waybillNo })
      set({ waybillStatusOverview: res?.statusODTOList || [] })
    },
    // 轨迹模块
    waybillPublishPath: [],
    getEventList: async (waybillNo: string) => {
      const res = await apiGetWaybillPublishPath({ waybillNo })
      set({ waybillPublishPath: res || [] })
    },
  }
})
